package com.aeks.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aeks.divide.FileDivide;
import com.aeks.finalkey.InsertData;
import com.aeks.user.AboutUser;
import com.aeks.user.User;
import com.xjt.nlp.word.ICTCLAS;

public class GetKeyServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		HttpSession session = request.getSession();
		String username = (String)session.getAttribute("username");
		
		String fileID = (String)request.getParameter("fileid");
		String saveName = (String)request.getParameter("savename");
		String servletPath = this.getServletContext().getRealPath("/");// 获得服务器所在地址
		
		String path = servletPath + "tempFile";
		String titleFile = path + "\\" + saveName + "titlePart.txt";
		String briefFile = path + "\\" + saveName + "briefPart.txt";
		String keyFile = path + "\\" + saveName + "keyPart.txt";
		String textFile = path + "\\" + saveName + "textPart.txt";
		
		File tf = new File(titleFile);
		File bf = new File(briefFile);
		File kf = new File(keyFile);
		File ttf = new File(textFile);
		
		String ts = this.getSplit(tf);
		String bs = this.getSplit(bf);
		String ks = this.getSplit(kf);
		String tts = this.getSplit(ttf);
		
		
		List<String> slist = new ArrayList<String>();
		System.out.println("t:" + ts);
		String tresult[] = ts.split("  ");
		List<String> tlist = FileDivide.deleteStop(tresult, slist, servletPath);
		System.out.println(tlist.size());
		
		System.out.println("b:" +bs);
		String bresult[] = bs.split("  ");
		List<String> blist = FileDivide.deleteStop(bresult, slist, servletPath);
		System.out.println(blist.size());
		
		System.out.println("k:" +ks);
		String kresult[] = ks.split("  ");
		List<String> klist = FileDivide.deleteStop(kresult, slist, servletPath);
		System.out.println(klist.size());
		
		System.out.println("tt:" +tts);
		String ttresult[] = tts.split("  ");
		List<String> ttlist = FileDivide.deleteStop(ttresult, slist, servletPath);
		System.out.println(ttlist.size());
		
		List<String> alist = new ArrayList<String>();//所有链表中的元素放在一个大的链表中
		alist.addAll(tlist);
		alist.addAll(blist);
		alist.addAll(klist);
		alist.addAll(ttlist);
		
		System.out.println(alist.size());
		if(alist != null && alist.size() > 0) {
			FileDivide.inputStopFile(alist, path, saveName);
		} 
		
		List<User> ulist = AboutUser.getUser(username);
		User u = null;
		if(ulist != null && ulist.size()>0) {
			u = ulist.get(0);
		}
		
		boolean isSuccess = countFrequency(alist, tlist, blist, klist, ttlist, u, fileID);
		System.out.println(isSuccess);
		if(isSuccess) {
			out.println("<script language='javascript'>");
			out.println("alert('处理文献成功！');");
			out.println("window.location.href='main.jsp?action=dealSuccess&fileID=" + fileID + "'");
			out.println("</script>");
		} else {
			out.println("<script language='javascript'>");
			out.println("alert('不能获取正确处理该文献！');");
			out.println("window.location.href='main.jsp'");
			out.println("</script>");
		}
		
		out.flush();
		out.close();
	}
	
	private String getSplit(File f) {
		String str = "";
		FileReader fr;
		try {
			fr = new FileReader(f);
			BufferedReader br = new BufferedReader(fr);
			ICTCLAS split1 = new ICTCLAS();
			String s = br.readLine();
			while(s != null) {
				s = split1.paragraphProcess(s);
				str += s;
				s = br.readLine();
			}
			//System.out.println(str);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return str;
	}
	
	private boolean countFrequency(List<String> alist, List<String> tlist, List<String> blist, List<String> klist, List<String> ttlist, User u, String fileID) {
		int count = tlist.size() + blist.size() + klist.size() + ttlist.size();
		
		
		Map<String, Integer> map = new HashMap<String, Integer>();//装计算了的备选关键字的值
		List<Map> amlist = new ArrayList<Map>();
		float lvalue = u.getLimitValue();
		getCount(tlist, alist, amlist, map, u.getTitleValue(), lvalue);
		getCount(blist, alist, amlist, map, u.getBriefValue(), lvalue);
		getCount(klist, alist, amlist, map, u.getKeyValue(), lvalue);
		getCount(ttlist, alist, amlist, map, u.getTextValue(), lvalue);
		
		System.out.println(amlist.size());
		if(InsertData.insertFinalKey(amlist, fileID)) {
			return true;
		} else {
			return false;
		}
		
	}
	
	private boolean getCount(List<String> list, List<String> alist, List<Map> mlist, Map<String, Integer> map, float value, float lvalue) {
		for(int i=0; i<list.size(); i++) {
			String s = list.get(i);
			
			if(!map.containsKey(s)) {//该关键字没有计算过
				//System.out.println(s);
				map.put(s, s.length());
				int n = 0;
				for(int j=0; j<alist.size(); j++) {
					String as = alist.get(j);
					if(s.equals(as)) {
						n ++;
					}
				}
				
				double freq = (n * 1.0) / alist.size(); 
				double cvalue = freq * value;
				String isKey = "0";
				if(cvalue >= lvalue) {
					isKey = "1";
					System.out.println(s);
					Map<Object, Object> map2 = new HashMap<Object, Object>();
					map2.put("keyvalue", s);
					map2.put("length", s.length());
					map2.put("freq", freq);
					map2.put("cvalue", cvalue);
					map2.put("iskey", isKey);
					mlist.add(map2);
				}
			}
		}
		return false;
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

}
